package com.alibaba.nacos;

import com.alibaba.nacos.api.NacosFactory;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.config.listener.Listener;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingFactory;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.listener.Event;
import com.alibaba.nacos.api.naming.listener.EventListener;
import com.alibaba.nacos.api.naming.listener.NamingEvent;

import java.util.Properties;
import java.util.concurrent.Executor;

public class JavaNacosTest {
    public static void main(String[] args) throws NacosException {
        // 服务注册
        NamingService namingService = NamingFactory.createNamingService("localhost:8848");
        namingService.registerInstance("app1", "11.11.11.11", 8888);
        // 服务发现
        namingService.getAllInstances("app1");
        // 订阅服务
        namingService.subscribe("app1", new EventListener() {
            @Override
            public void onEvent(Event event) {
                NamingEvent namingEvent = (NamingEvent) event;
                int size = namingEvent.getInstances().size();
                System.out.println(size);
            }
        });
        // 服务监听
        try {
            String serverAddr = "localhost:8848";
            String dataId = "user.properties";
            String group = "DEFAULT_GROUP";
            Properties properties = new Properties();
            properties.put("serverAddr", serverAddr);
            ConfigService configService = NacosFactory.createConfigService(properties);
            String content = configService.getConfig(dataId, group, 5000);
            System.out.println(content);
            configService.addListener(dataId, group, new Listener() {

                public void receiveConfigInfo(String configInfo) {
                    System.out.println("recieve1:" + configInfo);
                }

                public Executor getExecutor() {
                    return null;
                }
            });

            // 测试让主线程不退出，因为订阅配置是守护线程，主线程退出守护线程就会退出。 正式代码中⽆需下⾯代码
            while (true) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        } catch (NacosException e) {
            e.printStackTrace();
        }
    }
}
